#!/usr/bin/python

"""
    @author kyw
    @file log.py
    @createTime 2018/11/25 18:55
"""

import os
import logging
import logging.handlers
from .config import LOG_PATH, Config


class Logger(object):
    def __init__(self, logger_name='AutoTest'):
        self.logger = logging.getLogger(logger_name)
        logging.root.setLevel(logging.NOTSET)
        conf = Config().get('log')
        self.log_file_name = conf.get('file_name') if conf and conf.get('file_name') else 'autotest.log'  # 日志文件名
        self.back_up = conf.get('back_up') if conf and conf.get('back_up') else 6  # 备份日志数

        self.console_level = conf.get('console_level') if conf and conf.get('console_level') else 'DEBUG'  # 控制台日志级别
        self.file_level = conf.get('file_level') if conf and conf.get('file_level') else 'DEBUF'  # 文件输出日志级别

        self.pattern = conf.get('pattern') if conf and conf.get(
            'pattern') else '%(asctime)s - %(module)s - %(levelname)s : %(message)s'  # 日志默认输出格式
        self.logformart = logging.Formatter(self.pattern)

    def get(self):
        if not self.logger.handlers:
            # 设置控制台日志
            console_log = logging.StreamHandler()
            console_log.setFormatter(self.logformart)
            console_log.setLevel(self.console_level)
            self.logger.addHandler(console_log)

            # 设置日志文件
            file_log = logging.handlers.TimedRotatingFileHandler(filename=os.path.join(LOG_PATH, self.log_file_name),
                                                                 when='MIDNIGHT',
                                                                 backupCount=self.back_up,
                                                                 encoding='utf-8',
                                                                 delay=True)
            file_log.setFormatter(self.logformart)
            file_log.setLevel(self.file_level)
            self.logger.addHandler(file_log)
        return self.logger


logging = Logger().get()
